// stock/receive_send_summary/receive_send_summary.js
let listBehavior = require('../../behavior/list')

let { formatDate, getMonthFirstDate, getMonthLastDate, } = wx.$util,
  first = formatDate(getMonthFirstDate(), 'yyyy-MM-dd'),
  last = formatDate(getMonthLastDate(), 'yyyy-MM-dd')

Page({
  behaviors: [ listBehavior, ],

  /**
   * 页面的初始数据
   */
  data: {

    list: [],

    //搜索商品
    keyList: [
      {field_id: 'goods_id',field_name: '商品编码'},
      {field_id: 'goods_name',field_name: '商品名称'}
    ],
    //快速搜索
    searchList: [
      {field_id: 'date',type: 'date',field_name: '单据日期',start: first, end: last,},
      {field_id: 'quote_Warehouse',type: 'reference1',mainEntity: 'Warehouse',showFields: 'warehouse_name',field_name: '仓库',optionList: [],optionName: 'warehouse_name',optionId: 'row_id'},
      {field_id: 'table_id',type: 'reference1',field_name: '业务类型',
        optionList: [
          {'table_name': '商品期初库存','table_id': 'goods_opening_balance'},
          {'table_name': '组装单','table_id': 'assembly_order'},
          {'table_name': '组装单明细','table_id': 'assembly_order_details'},
          {'table_name': '拆装单','table_id': 'disassembly_order'},
          {'table_name': '拆装单明细','table_id': 'disassembly_order_details'},
          {'table_name': '调拨单','table_id': 'transfer_order'},
          {'table_name': '调拨单明细','table_id': 'transfer_order_details'},
        ],optionName: 'table_name',optionId: 'table_id'}
    ],

    //提交搜索数据
    searchObj: {
      date_s: first,  //开始日期
      date_e: last, //结束日期
      good_list: '',  //商品列表
      is_nothappen_notshow: '', //无发生额不显示
      quote_Warehouse: '',  //仓库
      table_id: ''  //业务类型
    },
    goodsList: [],  //商品列表

    displayField: [ //显示字段竖向
      {field_id: 'goods_type_name',label: '商品类别',type: 'text'},
      {field_id: 'goods_model_name',label: '规格',type: 'text'},
      {field_id: 'goods_unit_name',label: '单位',type:'text'},
    ],
    displayField2: [//显示字段横向
      {field_id: 'warehouse_name',label: '仓库'},
    ],

    subDisplayField: [],  //期初、入库、出库、结存

    subCol:{ '入库': [], '出库': [] },  //入库、出库相关模块

    //合计
    sumList: [],  //底部合计
  },

  //展开收起
  toggleShow(e){
    let {index,type} = e.currentTarget.dataset;
    this.setData({[`list[${index}].${type}`]: !this.data.list[index][type]})
  },
  //无发生额不显示
  onRadioChange(e){
    this.setData({
      ['searchObj.is_nothappen_notshow']: e.detail,
    });
    this.getFirstPage();
  },

  //搜索数据
  searchData(e){
    let {detail} = e,
      {goodsList,searchObj} = this.data;
    let good_list = [],
      quote_Warehouse = [];

    //输入框搜商品
    if (detail.iptVal){
      wx.$each(goodsList,(i,item)=>{
        if (item.goods_id.indexOf(detail.iptVal) >= 0 || item.goods_name.indexOf(detail.iptVal) >= 0){
          good_list.push(item.row_id);
        }
      });
    }
    //快速查询
    wx.$each(detail.quick,(i,item)=>{
      let key = item.CompareWith;
      if (key === 'date'){
        if (item.Operator === '>='){ key = 'date_s'; }
        if (item.Operator === '<=') { key = 'date_e'; }
      }
      searchObj[key] = item.CompareValue;
    });

    searchObj.good_list = good_list.join(',');

    this.setData({searchObj});
    this.getFirstPage();

  },

  //跳转页面
  navTo(e){
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    })
  },

  //合计数据
  sumData(data){
    let {sumList} = this.data,
      key = ['期初_balance_quantity','期初_balance_price'],
      sum = [0,0];
    wx.$each(data,(i,item)=>{
      sum[0] = parseFloat(sum[0] + item[key[0]]);
      sum[1] = parseFloat((sum[1] + item[key[1]]).toFixed(2));
    });
    sumList = [
      {name: '期初数量',num: sum[0]},
      {name: '期初成本',num: sum[1]}
    ];
    this.setData({sumList});
  },

  getDataList(){
    let {searchObj} = this.data,
      post = {...searchObj};
    wx.$post(1,'Stock/query_goods_inout_details_entity',post).then(res=>{
      if (res.errcode != 0)return;
      let data = res.data.row || [];
      this.getSCol(res.data.sum);
      this.setData({ list: data,page:1,total:data.length,limit: data.length });

      this.sumData(data);
    })
  },

  getSCol(field){
    let nameArr = [],
      fieldList = [],
      fieldList2 = [],
      {subCol} = this.data,
      obj= {
        '入库': [],
        '出库': []
      }
    wx.$each(field,(i,item)=>{
      let arr = item.field_name && item.field_name.split('|');
      if (arr && arr[1]){ //表名_入库|数量、表名_入库|成本、表名_出库|数量、表名_出库|成本
        let name = arr[0],
          typeArr = name.split('_');
        if (typeArr[1]){
          fieldList.push({
            table_name: typeArr[0],
            type: typeArr[1],
            field: {field_id: item.field_id,label: arr[1]}
          })
        }else {
          let index = nameArr.indexOf(name),
            fieldObj = {field_id: item.field_id,label: arr[1]};
          if (index < 0){
            nameArr.push(name);
            fieldList2.push({ title: name, fields: [fieldObj] ,childField: name.indexOf('入库')>=0 ? '入库' : name.indexOf('出库')>=0 ? '出库': ''});
          }else {
            fieldList2[index].fields.push(fieldObj);
          }
        }
      }
    });
    wx.$each(fieldList,(i,item)=>{
      let index = subCol[item.type].findIndex(ite=>{
        return ite.title === item.table_name
      });
      if (index < 0){
        subCol[item.type].push({
          title: item.table_name,
          fields: [item.field]
        })
      } else {
        subCol[item.type][index].fields.push(item.field)
      }
    })
    this.setData({subCol,subDisplayField: fieldList2});
    console.log(subCol);
  },


  //获取下拉选项
  getOptionsList(arg){
    let [key,v,url,post,iseach,parse] = arg;
    return new Promise((resolve,reject) => {
      wx.$post(v, url, post).then(res=>{
        if (res.errcode != 0){
          reject();
          return;
        }
        let data = res.data.row || [],
          list = data;
        if (iseach){
          list = this.eachData(data,'row_id',parse);
        }
        resolve({[key]: list});
      });
    });
  },
  ready(){
    let parmaArr = [
      ['good_list',3,'DynamicQuery/query_dynamic_v1',{"oby": "goods.row_id desc","table_id": "goods","page":1,"limit":0}],  //商品
      ['quote_Warehouse',3,'DynamicQuery/query_dynamic_v1',{"oby": "Warehouse.row_id desc","table_id": "Warehouse","page":1,"limit":0}],  //仓库
      ['table_id',1,'Stock/query_stock_entity',{"row_id":0}],  //业务
    ];
    this.getOptionsList(parmaArr[0]).then(res=>{
      this.data.goodsList = res.good_list;
    });
    Promise.all([this.getOptionsList(parmaArr[1]),this.getOptionsList(parmaArr[2])]).then(res=>{
      let resObj = {};
      wx.$each(res,(i,item)=>{
        resObj = {...resObj,...item}
      });
      let searchList = this.data.searchList;
      wx.$each(searchList,(i,item)=>{
        if (resObj[item.field_id]){
          item.optionList = [...item.optionList,...resObj[item.field_id]];
        }
      });

      this.setData({
        searchList,
      });
    });
    this.getOptionsList(parmaArr[1]).then(res=>{
      this.setData({ [`searchList[1].optionList`]: res.quote_Warehouse });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.getDataList();
    this.ready();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
